<template>
    <div class="article-lists">
        <el-card class="!border-none" shadow="never">

            <el-form ref="formRef" class="mb-[-16px]" :model="queryParams" :inline="true">
                <el-form-item label="名称">
                    <el-input
                        class="w-[280px]"
                        v-model="queryParams.keys"
                        clearable
                        @keyup.enter="resetPage"
                    />
                </el-form-item>
                <el-form-item label="城市">
                    <el-input
                        class="w-[280px]"
                        v-model="queryParams.city"
                        clearable
                        @keyup.enter="resetPage"
                    />
                </el-form-item>
                
                <el-form-item>
                    <el-button type="primary" @click="resetPage">查询</el-button>
                    <el-button @click="resetParams">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card class="!border-none" shadow="never">
             <el-button type="primary" class="mb-4" @click="onAddAddress">
                <template #icon>
                    <icon name="el-icon-Plus"/>
                </template>
                新增地址
            </el-button>
            <el-table size="large" v-loading="pager.loading" :data="pager.lists">
                <el-table-column label="序号" type="index" :index="indexAdd" min-width="100" />
                <el-table-column label="城市" min-width="120" prop="city"></el-table-column>
                <el-table-column label="名称" min-width="220" prop="name"/>
                <el-table-column label="地址" min-width="250" prop="address"/>
                <el-table-column label="电话" min-width="140" prop="tel"></el-table-column>
                <el-table-column label="办理时间" min-width="180" prop="work_time"></el-table-column>
                <el-table-column label="操作" width="180" fixed="right">
                    <template #default="{ row }">
                        <el-button type="primary" link @click="handleSelectItem(row)">修改</el-button>
                        <el-button type="danger" link @click="handleDetele(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="flex justify-end mt-4">
                <pagination v-model="pager" @change="getLists" />
            </div>
        </el-card>
        <popup
            ref="popupRef"
            :title="formData.id == 0? '新增': '修改'"
            :async="true"
            width="550px"
            @confirm="handleSubmit"
        >
            <el-form ref="formEdit" :model="formData" label-width="84px" :rules="formRules">
                <el-form-item label="城市" prop="name">
                    <div class="w-80 city-select">
                        <el-cascader v-model="formData.area_data" :options="gongjuList" filterable @change="handleChange" />
                    </div>
                </el-form-item>
                <el-form-item label="名称" prop="name">
                    <div class="w-80">
                        <el-input v-model="formData.name" type="textarea" maxlength="30" show-word-limit placeholder="请输入名称" clearable />
                    </div>
                </el-form-item>
                <el-form-item label="地址" prop="address">
                    <div class="w-80">
                        <el-input
                            v-model="formData.address"
                            placeholder="请输入地址"
                            type="textarea"
                            show-word-limit
                            clearable
                        />
                        <el-button @click="focusAddress">地图选点</el-button>
                    </div>
                </el-form-item>
                <el-form-item label="电话" prop="tel">
                    <div class="w-80">
                        <el-input v-model="formData.tel" type="text" maxlength="30" show-word-limit placeholder="请输入名称" clearable />
                    </div>
                </el-form-item>
                <el-form-item label="办理时间" prop="work_time">
                    <div class="w-80">
                        <el-input v-model="formData.work_time" type="textarea" maxlength="50" show-word-limit placeholder="请输入名称" clearable />
                    </div>
                </el-form-item>
            </el-form>
        </popup>
        <map-area ref="mapArea" @save="mapInfo" />
    </div>
</template>
<script lang="ts" setup name="list">
import type { FormInstance } from 'element-plus'
import { getBankList, getBankInfo, saveBankInfo, delBankInfo, getTreeList } from '@/api/platformTool'
import { usePaging } from '@/hooks/usePaging'
import router, { getRoutePath } from '@/router'
import feedback from '@/utils/feedback'
import Popup from '@/components/popup/index.vue'
const popupRef = shallowRef<InstanceType<typeof Popup>>()
import MapArea from '@/components/map/index.vue'
const mapArea = ref()

const gongjuList:any = ref([])
const getCity = async () => {
    const res = await getTreeList({});
    res.map((item:any)=>{
        item.value = item.name;
        item.label = item.name;
        item.children = item.citylist;
        item.citylist.map((itemC:any)=>{
            itemC.value = itemC.name;
            itemC.label = itemC.name;
            itemC.children = itemC.arealist;
            itemC.arealist.map((itemD:any)=>{
                itemD.value = itemD.name;
                itemD.label = itemD.name;
            })
        })
    })
    console.log(res)
    gongjuList.value = res;
}
getCity()
const handleChange = (e:any) => {
    console.log(e)
}

const queryParams = reactive({
    keys: '',
    city: ''
})

const { pager, getLists, resetPage, resetParams } = usePaging({
    fetchFun: getBankList,
    params: queryParams
})

const indexAdd = (index: number) => {
    const page = pager.page // 当前页码
    const pagesize = pager.size // 每页条数
    return index + 1 + (page - 1) * pagesize
}

const onAddAddress = () => {
    formData.id = 0;
    formData.area_data = [];
    formData.name = '';
    formData.address = '';
    formData.tel = '';
    formData.work_time = '';
    formData.lon = '';
    formData.lat = '';
    formData.prov = '';
    formData.city = '';
    formData.area = '';
    popupRef.value?.open();
    formEdit.value?.clearValidate();
}
const formEdit = shallowRef<FormInstance>()
const formData:any = reactive({
    id: 0,
    area_data: [],
    name: '',
    address: '',
    tel: '',
    work_time: '',
    lon: '',
    lat: '',
    prov: '',
    city: '',
    area: ''
})
const validateMaxMore = (rule:any, value:any, callback:any) => {
    if (!value) {
        callback(new Error('不能为空'));
    } else if (!/^[0-9\-/]+$/.test(value)) {
        callback(new Error('请输入正确的格式，多个手机号用/分隔'));
    }else {
        callback();
    }
};
const formRules = {
    name: [{required: true, message: '请输入名称', trigger: ['blur']}],
    address: [{required: true, message: '请输入地址', trigger: ['blur']}],
    tel: [{required: true, validator: validateMaxMore, trigger: ['blur']}],
    work_time: [{required: true, message: '请输入办理时间', trigger: ['blur']}],
}
//点击选择地址
const focusAddress = (e: any) => {
    mapArea.value.keywords(formData.address);
    mapArea.value.dialogVisible(true);
}
// 地图信息返回
const mapInfo = async (data: any) => {
    // formData.address = data.name;
    formData.address = data.cityname + data.adname + data.address;
    formData.lon = data.location.lng;
    formData.lat = data.location.lat;
}
const handleSelectItem = async (row: any) => {
    const res = await getBankInfo({id: row.id})
    Object.keys(formData).forEach((key) => {
        formData[key] = res[key]
    })
    formData.area_data = [formData.prov, formData.city, formData.area]
    popupRef.value?.open()
    formEdit.value?.clearValidate();
}
const handleSubmit = async() => {
    await formEdit.value?.validate()
    formData.prov = formData.area_data[0];
    formData.city = formData.area_data[1];
    formData.area = formData.area_data[2];
    await saveBankInfo(formData)
    popupRef.value?.close();
    getLists()
}
const handleDetele = async (row:any) => {
    try{
        await feedback.confirm('删除之后该地址信息将会清空，不可恢复，请确认是否删除该地址信息？')
        await delBankInfo({
            id: row.id
        })
        getLists();
    }catch(error){
        console.log(error)
    }
}

onActivated(() => {
    getLists()
})

getLists()
</script>
<style lang="scss" scoped>
.txt{
    color: var(--el-color-primary);
}
.city-select{
    ::v-deep .el-cascader{
        width: 100%;
    }
}
</style>